import React, { Component } from 'react';
import TheQueryForm from '@/components/TheQueryForm';
import TheTableExtend from '@/components/TheTableExtend';
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import TheImage from '@/components/TheImage';
import ThePagination from "@/components/ThePagination";
import TheUpload from "@/components/TheUpload";
import { Table, Space, Radio, Modal, Select, message, Form, Input, Button } from "antd";
import { apiVerificationPersonnelInfoDeliverymanPage, apiDeliverymanCarInfoAdd, apiDeliverymanCarInfoBatchUpdateStatus, apiDeliverymanCarInfoPage, apiDeliverymanCarInfoView, apiDeliverymanCarInfoEdit } from '@/request/writeOff'
import store from "@/store/store"
import _ from 'lodash';
import { getDateTime3 } from '@/utils/getDate'

const { TextArea } = Input;
const { Option } = Select
export default class CarList extends Component {
    constructor(props) {
        super(props)
        this.formRef = React.createRef()
        this.bindDeliverFormRef = React.createRef()


        this.state = {
            columns: [

                {
                    title: "车辆ID",
                    dataIndex: "deliverymanCarId",
                    key: "deliverymanCarId",
                },
                {
                    title: "车辆图片",
                    dataIndex: "picture",
                    key: "picture",
                    render: (text) => {
                        return <TheImage src={text} width={80} height={80} />
                    }
                },
                {
                    title: "车辆品牌",
                    dataIndex: "brand",
                    key: "brand",
                },
                {
                    title: "车辆型号",
                    dataIndex: "model",
                    key: "model",
                },
                {
                    title: "车身颜色",
                    dataIndex: "color",
                    key: "color",
                },
                {
                    title: "车牌号",
                    dataIndex: "number",
                    key: "number",
                },
                {
                    title: "配送员名称",
                    dataIndex: "deliverymanName",
                    key: "deliverymanName",
                },
                {
                    title: "GPS设备ID",
                    dataIndex: "gpsDeviceId",
                    key: "gpsDeviceId",
                },
                {
                    title: "状态",
                    dataIndex: "status",
                    key: "status",
                    render: (text, render) => {
                        let status = ''
                        switch (text) {
                            case 1:
                                status = '启用'
                                break;
                            case 2:
                                status = '禁用'
                                break;
                            default:
                                break;
                        }
                        return status
                    }
                },
                {
                    title: "备注",
                    dataIndex: "remark",
                    key: "remark",
                },
                {
                    title: "创建时间",
                    dataIndex: "createTime",
                    key: "createTime",
                },

                {
                    title: "操作",
                    fixed: 'right',
                    render: (text, render) => {
                        return <div>
                            <TheButton haspermi={['writeOff:carlist:onView']} onClick={() => this.onView(render.deliverymanCarId)}>查看</TheButton>
                            <TheButton haspermi={['writeOff:carlist:bindDeliver']} onClick={() => this.bindDeliver(render.deliverymanCarId)}>绑定配送员</TheButton>
                            <TheButton haspermi={['writeOff:carlist:onStatus']} onClick={() => this.onStatus(render)}>{render.status === 1 ? "禁用" : "启用"}</TheButton>
                            <TheButton haspermi={['writeOff:carlist:onEdit']} onClick={() => this.onEdit(render.deliverymanCarId)}>编辑</TheButton>
                        </div>
                    }
                },
            ],
            newColumns: [],
            dataSource: [],
            form_show: true,
            queryForm: {},
            searchOption: [
                { field: 'keyword', label: '搜索', placeholder: '请输入搜索关键字', required: false, rules: [], type: 'Input', defaultValue: '', tooltip: "包含车辆品牌，车辆型号" },
                { field: 'time', label: '创建时间', placeholder: '', required: false, rules: [], type: 'RangePicker', defaultValue: '' },
                { field: 'status', label: '状态', placeholder: '', required: false, rules: [], options: [{ label: '全部', value: '' }, { label: '启用', value: 1 }, { label: '禁用', value: 2 }], type: 'Select', defaultValue: '' },
            ],
            pageData: {
                pageNo: 1,
                pageSize: 10
            },
            total: 0,
            isModalShow: false,
            viewModalShow: false,
            bindDeliverModalShow: false,
            delivers: [],
            picture: [],
            type: '',
            deliverymanCarId: '',
            loading: false,
            selectedRowKeys: []
        }
    }
    componentDidMount() {
        this.getData()
        this.onColumnsFilter(this.state.columns)
    }
    async getDeliverData() {
        const res = await apiVerificationPersonnelInfoDeliverymanPage({ pageSize: -1 })
        if (res.code === 0) {
            this.setState({
                delivers: res.data
            })
        }
    }
    async getData(values) {
        const { pageNo, pageSize } = this.state.pageData
        if (values && !_.isEmpty(values.time)) {
            values.startCreateTime = getDateTime3(values.time[0]) + ' 00:00:00'
            values.endCreateTime = getDateTime3(values.time[1]) + ' 23:59:59'
            delete values.time
        }
        this.setState({
            queryForm: values === undefined ? this.state.queryForm : { ...values }
        }, async () => {
            const params = {
                pageNo, pageSize, queryForm: this.state.queryForm
            }
            store.dispatch({
                type: 'SaveSearchValues',
                data: {
                    pathName: 'writeCarList',
                    ...params
                }
            })
            
            const res = await apiDeliverymanCarInfoPage({ pageNo, pageSize, ...this.state.queryForm })
            if (res.code === 0) {
                this.setState({
                    dataSource: res.data,
                    total: res.totalCount,
                    selectedRowKeys:[]
                })
                this.getDeliverData()

            }
        })

    }
    async onStatus(render) {
        const res = await apiDeliverymanCarInfoEdit({ ...render, status: render.status === 1 ? 2 : 1 })
        if (res.code === 0) {
            message.success('操作成功')
            this.getData()
        }
    }
    async bindDeliver(deliverymanCarId) {

        const res = await apiDeliverymanCarInfoView({ deliverymanCarId })
        if (res.code === 0) {
            this.setState({
                type: 'onBindDeliver',
                bindDeliverModalShow: true,
                deliverymanCarId
            }, () => {
                this.bindDeliverFormRef.current.setFieldsValue({
                    ...res.data
                })
            })

        }


    }
    async onEdit(deliverymanCarId) {
        const res = await apiDeliverymanCarInfoView({ deliverymanCarId })
        if (res.code === 0) {
            this.setState({ picture: [], isModalShow: true, deliverymanCarId }, () => {
                this.setState({
                    type: 'onEdit',
                    picture: res.data.picture ? res.data.picture.split(',').map(v => {
                        return {
                            uid: new Date().getTime(),
                            name: 'image',
                            status: 'done',
                            url: v
                        }
                    }) : [],
                }, () => {
                    console.log(this.state.picture);
                    this.formRef.current.setFieldsValue({
                        ...res.data
                    })
                })
            })

        }
    }
    async onView(deliverymanCarId) {
        const res = await apiDeliverymanCarInfoView({ deliverymanCarId })
        if (res.code === 0) {
            this.setState({ picture: [], type: 'onView', viewModalShow: true, picture: [res.data.picture] }, () => {
                this.formRef.current.setFieldsValue({
                    ...res.data, status: res.data.status === 1 ? '启用' : '禁用'
                })

            })
        }
    }
    onColumnsFilter(value) {
        this.setState({
            newColumns: value
        })
    }
    pageChange = (pageNo, pageSize) => {
        this.setState({
            pageData: {
                pageNo, pageSize
            }
        }, () => {
            this.getData()
        })
    }
    //重置
    onReset() {
        this.setState({
            status: "",
            queryForm: {}
        }, () => {
            this.pageChange(1, 10)
        })
    }
    //搜索
    onFormSearch(values) {
        this.setState({
            pageData: { pageNo: 1, pageSize: this.state.pageData.pageSize }
        }, () => this.getData(values))

    }
    add() {
        this.setState({
            picture: [],
            type: 'onAdd',
            isModalShow: true
        })
    }
    async allEditStatus(status) {
        if(this.state.selectedRowKeys.length === 0) return
        this.setState({ loading: true })
        const res = await apiDeliverymanCarInfoBatchUpdateStatus({ carIds: this.state.selectedRowKeys, status })
        if (res.code === 0) {
            this.setState({
                selectedRowKeys: [],
                loading: false
            }, () => {
                this.getData()
            })
            message.success('操作成功')
        }
    }
    handleOk() {
        this.formRef.current.validateFields().then(async values => {
            this.setState({ loading: true })

            if (this.state.type == 'onAdd') {
                const res = await apiDeliverymanCarInfoAdd({ ...values })
                if (res.code === 0) {
                    this.formRef.current.resetFields()

                    this.setState({
                        isModalShow: false,
                        picture: [],
                        loading: false
                    })
                    message.success('操作成功')
                }
            } else if (this.state.type == 'onEdit') {
                const res = await apiDeliverymanCarInfoEdit({ ...values, deliverymanCarId: this.state.deliverymanCarId })
                if (res.code === 0) {
                    this.formRef.current.resetFields()
                    this.setState({
                        isModalShow: false,
                        picture: [],
                        loading: false

                    })
                    message.success('操作成功')
                }
            }
            this.getData()
        })
    }
    handleCancel() {
        setTimeout(()=>{
            this.formRef.current.resetFields();
        },1000)
        this.setState({
            isModalShow: false,
            picture: []
        })
    }
    handleBindOk() {
        this.bindDeliverFormRef.current.validateFields().then(async values => {
            if (this.state.type == 'onBindDeliver') {
                this.setState({ loading: true })
                const res = await apiDeliverymanCarInfoEdit({ ...values, deliverymanCarId: this.state.deliverymanCarId })
                if (res.code === 0) {
                    message.success('操作成功')
                    this.getData()
                    this.setState({
                        bindDeliverModalShow: false,
                        loading: false
                    })
                }
            }
        })

    }
    getFileResult = (value, key) => {
        if (value.length > 0 && value[0].hasOwnProperty('response')) {
            this.formRef.current.setFieldsValue({
                [key]: value[0].response.data
            })
        } else {
            this.formRef.current.setFieldsValue({
                [key]: ''
            })
        }
    };
    onSelect = (record, selected, selectedRows) => {
        this.setState({
            selectedRowKeys: selectedRows.map(item => item.deliverymanCarId)
        })
    }
    onSelectAll = (selected, rows, newRow) => {
        this.setState({
            selectedRowKeys: rows.map(item => item.deliverymanCarId)
        })
    }
    render() {
        const { selectedRowKeys, loading, form_show,type, searchOption, newColumns, pageData, total, dataSource, isModalShow, bindDeliverModalShow, viewModalShow, delivers, picture } = this.state
        const rowSelection = {
            selectedRowKeys,
            onSelect: this.onSelect,
            onSelectAll: this.onSelectAll
        };
        return (
            <div className='p-layout-box commodity-examine' ref={this.pageHeight}>
                <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
                    onReset={() => this.onReset()}
                    onGetValues={(values) => this.onFormSearch(values)} >
                </TheQueryForm>
                <TheTableExtend
                    columns={newColumns}
                    onFormTrigger={() => this.setState({ form_show: !this.state.form_show })}
                    onTableRefresh={() => this.getData()}
                    onColumnsFilter={(value) => this.onColumnsFilter(value)}
                >
                    <TheButton haspermi={['writeOff:carlist:add']} size="middle" onClick={() => this.add()} type="primary">添加</TheButton>
                    <TheButton disabled={!(Array.isArray(this.state.selectedRowKeys) && this.state.selectedRowKeys.length > 0)} haspermi={['writeOff:carlist:statusOn']} size="middle" onClick={() => this.allEditStatus(1)} type="default">启用</TheButton>
                    <TheButton disabled={!(Array.isArray(this.state.selectedRowKeys) && this.state.selectedRowKeys.length > 0)} haspermi={['writeOff:carlist:statusOff']} size="middle" danger onClick={() => this.allEditStatus(2)} type="primary">禁用</TheButton>

                </TheTableExtend>
                <TheTable columns={newColumns} dataSource={dataSource} pagination={false} bordered={1}
                    scroll={{ x: 'max-content', y: '55vh' }}
                    rowSelection={rowSelection}
                    rowKey={(record) => record.deliverymanCarId}
                ></TheTable>
                <ThePagination
                    pageNo={pageData.pageNo}
                    pageSize={pageData.pageSize}
                    total={total}
                    pageChange={this.pageChange}

                />
                <Modal title={type==='onAdd'?'新增':'编辑'} visible={isModalShow} onCancel={() => this.handleCancel()}

                    footer={[
                        <Button key="back" onClick={() => this.handleCancel()}>
                            取消
                        </Button>,
                        <Button key="submit" type="primary" loading={loading} onClick={() => this.handleOk()}>
                            保存
                        </Button>,

                    ]}
                >
                    <Form
                        ref={this.formRef}
                        labelCol={{
                            span: 6,
                        }}
                        wrapperCol={{
                            span: 16,
                        }}
                        initialValues={{
                            status: 1,
                            remark: ''
                        }}
                        onFinish={this.onFinish}
                        autoComplete="off"
                    >
                        <Form.Item
                            label="车辆图片"
                            name="picture"
                            extra={`图片尺寸建议800*800像素，仅支持gif、jpeg、png、bmp 格式，大小不超过3M`}
                            rules={[
                                {
                                    required: true,
                                    message: '请上传车辆图片!',
                                },
                            ]}
                        >
                            <TheUpload fileList={picture} getFileResult={(e) => this.getFileResult(e, 'picture')} len={1} />

                        </Form.Item>
                        <Form.Item
                            label="车辆品牌"
                            name="brand"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入车辆品牌!',
                                },
                            ]}
                        >
                            <Input showCount maxLength={120} />
                        </Form.Item>
                        <Form.Item
                            label="车辆型号"
                            name="model"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入车辆型号!',
                                },
                            ]}
                        >
                            <Input showCount maxLength={120} />
                        </Form.Item>
                        <Form.Item
                            label="车身颜色"
                            name="color"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入车身颜色!',
                                },
                            ]}
                        >
                            <Input showCount maxLength={120} />
                        </Form.Item>
                        <Form.Item
                            label="车牌号"
                            name="number"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入车牌号!',
                                },
                            ]}
                        >
                            <Input showCount maxLength={120} />
                        </Form.Item>
                        <Form.Item
                            label="所属配送员"
                            name="deliverymanId"
                            rules={[
                                {
                                    required: true,
                                    message: '请选择所属配送员!',
                                },
                            ]}
                        >
                            <Select optionLabelProp="label" showSearch filterOption={(input, option) =>
                                (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                            }>
                                {
                                    delivers.map(item => {
                                        return <Option value={item.deliverymanId} label={item.name} disabled={item.deliverymanCarId}>
                                            <Space

                                                style={{ display: 'flex', justifyContent: 'space-between' }}>
                                                {item.name}
                                                <span style={{ color: item.deliverymanCarId ? '#999' : '#333', marginLeft: 20 }}>
                                                    {item.deliverymanCarId ? '已绑定' : '未绑定'}
                                                </span>
                                            </Space>
                                        </Option>
                                    })
                                }
                            </Select>
                        </Form.Item>
                        <Form.Item
                            label="GPS设备"
                            name="gpsDeviceId"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入GPS设备ID!',
                                },
                            ]}
                        >
                            <Input showCount maxLength={32} />
                        </Form.Item>
                        <Form.Item
                            label="是否启用"
                            name="status"
                        >
                            <Radio.Group >
                                <Radio value={1}>启用</Radio>
                                <Radio value={2}>禁用</Radio>
                            </Radio.Group>
                        </Form.Item>
                        <Form.Item
                            label="备注"
                            name="remark"
                        >
                            <TextArea rows={4} showCount maxLength={200} />
                        </Form.Item>
                    </Form>
                </Modal>
                <Modal title="查看详情" visible={viewModalShow} onOk={() => this.setState({ viewModalShow: false })} onCancel={() => this.setState({ viewModalShow: false })}>
                    <Form
                        ref={this.formRef}
                        labelCol={{
                            span: 6,
                        }}
                        wrapperCol={{
                            span: 16,
                        }}
                        autoComplete="off"
                    >
                        <Form.Item
                            label="车辆图片"
                            name="picture"
                        >
                            {
                                picture.map(item => <TheImage src={item} width={80} height={80} />)
                            }

                        </Form.Item>
                        <Form.Item
                            label="车辆品牌"
                            name="brand"

                        >
                            <Input readOnly bordered={false} />
                        </Form.Item>
                        <Form.Item
                            label="车辆型号"
                            name="model"

                        >
                            <Input readOnly bordered={false} />
                        </Form.Item>
                        <Form.Item
                            label="车身颜色"
                            name="color"

                        >
                            <Input readOnly bordered={false} />
                        </Form.Item>
                        <Form.Item
                            label="车牌号"
                            name="number"

                        >
                            <Input readOnly bordered={false} />
                        </Form.Item>
                        <Form.Item
                            label="所属配送员"
                            name="deliverymanId"

                        >
                            {/* <Input readOnly bordered={false} /> */}
                            <Select readOnly bordered={false}>
                                {
                                    delivers.map(item => {
                                        return <Option value={item.deliverymanId} label={item.name} disabled={item.deliverymanCarId}>
                                            <Space>
                                                {item.name}

                                            </Space>
                                        </Option>
                                    })
                                }
                            </Select>
                        </Form.Item>
                        <Form.Item
                            label="GPS设备"
                            name="gpsDeviceId"
                        >
                            <Input readOnly bordered={false} />
                        </Form.Item>
                        <Form.Item
                            label="是否启用"
                            name="status"
                        >
                            <Input readOnly bordered={false} />

                        </Form.Item>
                        <Form.Item
                            label="备注"
                            name="remark"
                        >
                            <Input readOnly bordered={false} />
                        </Form.Item>
                    </Form>
                </Modal>
                <Modal title="绑定配送员"
                    visible={bindDeliverModalShow}
                    onCancel={() => this.setState({ bindDeliverModalShow: false })}
                    footer={[
                        <Button key="back" onClick={() => this.setState({ bindDeliverModalShow: false })}>
                            取消
                        </Button>,
                        <Button key="submit" type="primary" loading={loading} onClick={() => this.handleBindOk()}>
                            保存
                        </Button>,

                    ]}
                >
                    <Form
                        ref={this.bindDeliverFormRef}
                        labelCol={{
                            span: 6,
                        }}
                        wrapperCol={{
                            span: 16,
                        }}
                        autoComplete="off"
                    >
                        <Form.Item
                            label="所属配送员"
                            name="deliverymanId"
                        >
                            <Select >
                                {
                                    delivers.map(item => {
                                        return <Option value={item.deliverymanId} label={item.name} disabled={item.deliverymanCarId}>
                                            <Space style={{ display: 'flex', justifyContent: 'space-between' }}>
                                                {item.name}
                                                <span style={{ color: item.deliverymanCarId ? '#999' : '#333', marginLeft: 20 }}>
                                                    {item.deliverymanCarId ? '已绑定' : '未绑定'}
                                                </span>
                                            </Space>
                                        </Option>
                                    })
                                }
                            </Select>

                        </Form.Item>

                    </Form>
                </Modal>
            </div>
        );
    }
}
